package com.hujf.yarn;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.Tool;

import java.io.IOException;

/**
 * @author Hujf
 * @title: WordCount
 * @date 2021/4/69:33
 * @description: TODO
 */
public class WordCount implements Tool {

    private Configuration conf;
    //核心驱动conf 上下文中传入
    @Override
    public int run(String[] args) throws Exception {
        Job job = Job.getInstance(conf);

        job.setJarByClass(WordCountJar.class);

        job.setMapperClass(WordCountMapper.class);

        job.setReducerClass(WordReduce.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.setInputPaths(job,new Path(args[0]));
        FileOutputFormat.setOutputPath(job,new Path(args[1]));
        return job.waitForCompletion(true)?0:1;
    }

    @Override
    public void setConf(Configuration conf) {
        this.conf=conf;
    }

    @Override
    public Configuration getConf() {
        return conf;
    }

    //mapper

    //reduce
    public static class WordCountMapper extends Mapper<LongWritable, Text,Text, IntWritable> {
        private Text text = new Text();
        private IntWritable num = new IntWritable(1);
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String s = value.toString();
            String[] s1 = s.split(" ");
            for(String word :s1){
                text.set(word);
                context.write(text,num);
            }
        }
    }

    public static class WordReduce extends Reducer<Text,IntWritable,Text,IntWritable>{
        private IntWritable nums = new IntWritable();
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int num = 0;
            for (IntWritable value : values) {
                num++;
            }
            nums.set(num);
            context.write(key,nums);
        }
    }
}
